<?php
namespace App\DBs\Stock;

use Illuminate\Support\Facades\DB;

class SourceDB extends BaseDB
{
    /**
     * 创板素材字段
     * uid 用户UID
     * vid 库视频ID
     * plus 创作ID
     * bid 创板ID
     * serial 编号顺序
     * type 1素材地址，2文字，
     * link 素材地址
     */

    protected $table = 'stock_source';
    protected $tStock = 'stock'; //库

    public function __construct()
    {
    }

    /**
     * APP列表
     */
    public function getAppIndex($uid, $bid)
    {
        //库信息
        $resStocks = DB::table($this->tStock)->where('del',0)
            ->where('id',0)->get();
        //素材列表
        $query = DB::table($this->table)->where('del',0)
            ->where('bid',$bid)
            ->where('uid',$uid);
        $queryTotal = $query->count();
        $models = $query->orderBy('serial','asc')->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $dataArr = array();
        foreach ($models as $model) {
            $link = $model['type']==1 ? env('DOMAIN').$model['link'] : $model['link'];
            $dataArr[] = [
                'serial' => $model['serial'],
                'type' => $model['type'],
                'link' => $link,
            ];
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr, 'total'=>$queryTotal);
    }

    /**
     * APP一条
     */
    public function getAppOne($sid)
    {
        $models = DB::table($this->table)->where('del',0)
            ->where('id',$sid)->orderBy('serial','asc')
            ->skip(0)->take(1)
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $model = $this->jsonToArr($models[0]);
        $dataArr = [
            'serial' => $model['serial'],
            'type' => $model['type'],
            'link' => $model['link'],
        ];
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * APP更新
     * @param $id 素材ID
     * @param $itams 更新的数据
     */
    public function setUpdate($id, $items)
    {
        if (!$id || !$items) {
            return array('code'=>'-1', 'msg'=>'参数错误');
        }
        $t = time();
        $items['created_at'] = $t;
        //开启事务
        DB::beginTransaction();
        try {
            //去除老数据
            DB::table($this->table)->where('id', $id)
                ->update(['del'=>1 ,'updated_at'=>$t]);
            //新增数据
            $lastId = DB::table($this->table)->insertGetId($items);
            $dataArr = array(
                'lastId' => $lastId,
            );
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }
}